package com.cst.zju.anime.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cst.zju.anime.dao.AnimeAndTagsMapper;
import com.cst.zju.anime.dao.AnimeMapper;
import com.cst.zju.anime.dao.TagsMapper;
import com.cst.zju.anime.model.Anime;
import com.cst.zju.anime.model.AnimeAndTagsExample;
import com.cst.zju.anime.model.AnimeExample;
import com.cst.zju.anime.model.Tags;
import com.cst.zju.anime.model.TagsExample;
import com.cst.zju.anime.service.ITagsService;
@Transactional
@Service("iTagsService")
public class TagsService implements ITagsService {

	@Resource
	private TagsMapper tagsMapper;
	
	@Resource
	private AnimeAndTagsMapper animeAndTagsMapper;
	
	@Resource 
	private AnimeMapper animeMapper;
	
	@Override
	public Tags getTagsById(int id) {
		return tagsMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Tags> getAllTags() {
		return tagsMapper.selectByExample(new TagsExample());
	}

	@Override
	public List<Anime> getAnimeByTagName(String name) {
		TagsExample tagsExample = new TagsExample();
		tagsExample.createCriteria().andNameLike("%" + name + "%");
		List<Tags> list = tagsMapper.selectByExample(tagsExample);
		if(list.isEmpty()){
			return new ArrayList<Anime>();
		}
		List<Integer> idList = new ArrayList<Integer>(); 
				
		list.forEach((Tags tag) -> {idList.add(tag.getId());});
		
		AnimeAndTagsExample animeAndTagsExample = new AnimeAndTagsExample();
		animeAndTagsExample.createCriteria().andTagsIdIn(idList);
		List<Integer> animeIdList = animeAndTagsMapper.selectAnimeIdByExample(animeAndTagsExample);
		
		AnimeExample animeExample = new AnimeExample();
		animeExample.createCriteria().andIdIn(animeIdList);
		return animeMapper.selectByExample(animeExample);
	}

}
